import { computed, ref } from "vue";
import formData from "@/tool/data/formData";
import type { Form } from "@/interface/formData";
import axios from "axios";
import { useUserStore } from "@/stores/userStore";
import { dayjs, ElMessage } from "element-plus";


export default function () {
    const { useridentityfer } = useUserStore();
    const form = formData();


    //后端请求=======================================================================
    async function getReceiveJobs() {
        await axios.get(`/api/student/myWorks/${useridentityfer}`)
            .then(response => {
                TableDataAll.value = response.data.data;
                console.log("ReceiveJobs:", TableDataAll.value);
                formatTableData(TableDataAll.value);
            })
            .catch(error => {
                ElMessage.warning("获取已接取职位信息，请求失败");
            })
    }

    async function REQ_completeWork() {
        await axios.get(`/api/student/updateprocess/${currentRowData.value.id}/${currentRowData.value.process}`)
            .then(response => {
            })
            .catch(error => {
                ElMessage.warning("工作已完成，请求失败");
            })
    }




    // 搜索框=========================================================================

    //搜索框数据
    let title = ref("");
    let type = ref("");
    let priceLow = ref<number | null>(null);
    let priceHeight = ref<number | null>(null);
    const flitItem = ref({ title, type, priceLow, priceHeight });

    //搜索内容重置
    const resetForm = () => {
        title.value = "";
        type.value = "";
        priceLow.value = null;
        priceHeight.value = null;
    };



    //表格========================================================================

    const currentRowData = ref<Form>({
        //存储一条数据的变量
        id: 0,
        userIdentifier: 0,
        userName: "",
        jobType: "",
        status: "",
        title: "",
        maxPeople: 0,
        description: "",
        salary: 0,
        process: "",
        takersId: [],
        takersName: [],
        createdTime: new Date(),
        startTime: new Date(),
        endTime: new Date(),
        publishTime: new Date(),
        autoPublish: true,
    });

    const TableDataAll = ref<Form[]>([]);
    let formarTable = ref<Form[]>();


    function formatTableData(data: Form[]) {
        formarTable.value = data.map((item) => ({
            ...item,
            status: item.status === "1" ? "待审核" :
                item.status === "2" ? "审核通过" :
                    item.status === "3" ? "审核失败" : item.status,

            process: item.process === "1" ? "待审核" :
                item.process === "2" ? "已接取" :
                    item.process === "3" ? "进行中" :
                        item.process === "4" ? "已完成" :
                            item.process === "5" ? "已结算" :
                                item.process === "6" ? "审核失败" : item.process,

            jobType: item.jobType === "1" ? "零工" :
                item.jobType === "3" ? "短期兼职" :
                    item.jobType === "2" ? "长期兼职" : item.jobType,

            autoPublish: item.autoPublish,
        }))
    }

    // 表格状态的的排序
    function sortByProcess(a: Form, b: Form): number {
        const orderMap: Record<string, number> = {
            "2": 1, // 已接取
            "3": 2, // 进行中
            "4": 3, // 已完成
            "5": 4  // 已结算
        };
        const orderA = orderMap[a.process] ?? 99;
        const orderB = orderMap[b.process] ?? 99;
        return orderA - orderB;
    }


    function getTagType(process: string): string {
        switch (process) {
            case "待审核": return "info";       // 待审核
            case "已接取": return "warning";    // 橙色 已接取
            case "进行中": return "primary";    // 蓝色 进行中
            case "已完成": return "success";    // 绿色 已完成
            case "已结算": return "info";    //  已结算
            case "审核失败": return "danger";    //  审核失败
            default: return "danger";      // 红色代表异常或未知
        }
    }

    //表格数据

    //table数据过滤
    const tableData = computed(() => {
        if (
            !type.value &&
            !title.value &&
            !priceLow.value &&
            !priceHeight.value
        )
            return TableDataAll.value;
        return TableDataAll.value.filter((item: Form) => {
            const matchType = type.value
                ? item.jobType.includes(type.value)
                : true;
            const matchTitle = title.value
                ? item.title.includes(title.value)
                : true;
            const matchPriceMin = priceLow.value
                ? item.salary > priceLow.value
                : true;
            const matchPriceMax = priceHeight.value
                ? item.salary < priceHeight.value
                : true;
            return matchType && matchTitle && matchPriceMin && matchPriceMax;
        });
    });

    //价格的格式化展示
    const formatPrice = (row: Form, column: Form, cellValue: number) => {
        return `${cellValue}元/小时`;
    };


    const isOpenDrawer = ref(false);
    // 行点击函数
    const RowClick = (row: Form) => {
        isOpenDrawer.value = true;
        currentRowData.value = { ...row };
        console.log("当前行数据：", currentRowData.value)
    };

    const formattedCreatedAt = computed({
        get: () => dayjs(currentRowData.value.createdTime).format("YYYY-MM-DD"),
        set: (val) => {
            currentRowData.value.createdTime = dayjs(val, "YYYY-MM-DD").toDate();
        },
    });
    const formattedStartTime = computed({
        get: () => dayjs(currentRowData.value.startTime).format("YYYY-MM-DD"),
        set: (val) => {
            currentRowData.value.startTime = dayjs(val, "YYYY-MM-DD").toDate();
        },
    });
    const formattedPublishTime = computed({
        get: () => dayjs(currentRowData.value.publishTime).format("YYYY-MM-DD"),
        set: (val) => {
            currentRowData.value.publishTime = dayjs(val, "YYYY-MM-DD").toDate();
        },
    });

    const formatDrawerDate = ref({
        formattedCreatedAt: formattedCreatedAt,
        formattedStartTime: formattedStartTime,
        formattedPublishTime: formattedPublishTime,
    });


    const isEdit = ref(true);

    // 侧边栏================================================================
    async function handleCompleteWork() {
        console.log("process", currentRowData.value.process, "jobid", currentRowData.value.id);
        await REQ_completeWork(); // 等待完成
        await getReceiveJobs();   // 重新加载表格数据
        ElMessage.success("修改成功");
        isOpenDrawer.value = false;
    }





    // 举报功能========================================================
    const reportDialogVisible = ref(false);
    const reportFormRef = ref();
    const reportForm = ref({
        reason: "",
        files: [] as File[], // 这是 v-model:file-list 绑定的
    });

    // 文件上传限制逻辑
    const beforeUpload = (file: File) => {
        const isImage = file.type.startsWith("image/");
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isImage) {
            ElMessage.error("只能上传图片类型文件！");
        }
        if (!isLt2M) {
            ElMessage.error("上传文件大小不能超过 2MB！");
        }
        return isImage && isLt2M;
    };

    const handleRemoveFile = (file: any, fileList: File[]) => {
        reportForm.value.files = fileList;
    };

    // 提交举报
    const submitReport = async () => {
        await reportFormRef.value.validate(async (valid: boolean) => {
            if (!valid) return;

            const formData = new FormData();
            // formData.append("reason", reportForm.value.reason);
            // formData.append("targetUserId", currentRowData.value.userIdentifier.toString());
            // formData.append("jobId", currentRowData.value.id.toString());
            // formData.append("reportType", "1"); // 可按你需要设定类型
            // formData.append("reporterId", useUserStore().useridentityfer.toString()); // 当前登录用户ID


            const reportPayload = {
                  reportInfo: reportForm.value.reason,
                  targetUserId: currentRowData.value.userIdentifier,
                  applicantId: useridentityfer,
                  createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            };
            formData.append("reportInfo",  JSON.stringify(reportPayload));

            reportForm.value.files.forEach((file: any) => {
                formData.append("file", file.raw || file); // 使用 raw 获取原始文件
            });

            try {
                await axios.post("/api/jobTaker/repoort", formData, {
                    headers: { "Content-Type": "multipart/form-data" },
                });
                ElMessage.success("举报提交成功");
                reportDialogVisible.value = false;
                // 清空数据
                reportForm.value.reason = "";
                reportForm.value.files = [];
            } catch (error) {
                ElMessage.error("举报提交失败");
            }
        });
    };




    return {
        flitItem,
        tableData,
        currentRowData,
        formatDrawerDate,
        isEdit,
        isOpenDrawer,
        formarTable,
        handleCompleteWork,
        getTagType,
        sortByProcess,
        resetForm,
        formatPrice,
        getReceiveJobs,
        RowClick,
        // 举报功能
        reportDialogVisible,
        reportForm,
        reportFormRef,
        beforeUpload,
        handleRemoveFile,
        submitReport,
    };
}
